<script setup>
import {onMounted, ref} from "vue";
import searchList from '/components/search-list.vue'
import StudentItem from "@/components/student-item.vue";
import {getStudentListApi} from "@/api/student.js";
import {useStudentStroes} from "@/stores/modules/studentStroes.js";

const studentStore = useStudentStroes()

const list = ref([])
const getStudentList = async () => {
  const res = await getStudentListApi()
  list.value = res.data
}
const searchVal = ref('')
const stuList = ref([])

defineProps({
  value: {
    type: Number,
    required: true
  }
})
const emit = defineEmits(['update:value'])

const nextStep = () => {
  console.log('nextStep')
  studentStore.setStudentList(stuList.value)
  emit('update:value', 2)
}

const resList = ref([])
// todo: 此处存在搜索bug
const search = (e) => {
  searchVal.value = e
  resList.value = list.value.filter(item => (item.name.includes(searchVal.value) || item.stuid.includes(searchVal.value)))
}


const select = (e) => {
  searchVal.value = ''
  stuList.value.push(e)
}
const delId = ref(null)
const delNotice = ref(false)
const del = (id) => {
  delId.value = id
  delNotice.value = true
}
const confirm = () => {
  delNotice.value = false
  stuList.value = stuList.value.filter(item => item.id !== delId.value)
  uni.$u.toast('删除成功')
}
const init = () => {
  stuList.value = studentStore.studentList
}
onMounted(() => {
  getStudentList()
  init()
})
</script>

<template>
  <up-modal ref="uModal" :asyncClose="true" :show="delNotice" showCancelButton title="确认删除？"
            @cancel="delNotice = false"
            @confirm="confirm"></up-modal>
  <view class="search">
    <up-input
        custom-style="background:#fff;"
        fontSize="32rpx"
        placeholder="请输入学生姓名/学号关键词搜索添加"
        prefix-icon="search"
        prefix-icon-style="font-size:40rpx;"
        shape="circle"
        @change="search"></up-input>
  </view>
  <scroll-view v-if="!searchVal" class="list">
    <up-text :text="`已选择学生（${stuList.length}）`" bold margin="40rpx 0" size="26rpx"></up-text>
    <view v-if="stuList.length>0" class="list">
      <student-item :stu-list="stuList" @del="del"></student-item>
      <view class="btn">
        <up-button custom-style="background:#2e6bf8;height:90rpx" shape="circle" text="下一步" type="primary"
                   @click="nextStep"></up-button>
      </view>
    </view>
    <up-empty
        v-else
        icon="http://cdn.uviewui.com/uview/empty/list.png"
        mode="list"
    >
    </up-empty>
  </scroll-view>
  <searchList v-else :res-list="resList" @select="select"></searchList>
</template>

<style lang="scss" scoped>
.search {
  width: 100%;
  height: 80rpx;
}

.list {
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
    background-color: #fff;
    padding: 60rpx 30rpx;
    border-radius: 20rpx;
    margin: 20rpx 0;
  }

  .btn {
    position: fixed;
    bottom: 20rpx;
    width: 90%;
  }
}
</style>